package com.awspaas.user.apps.shhtaerospaceindustrial.event;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.listener.InterruptListenerInterface;
import com.actionsoft.bpms.commons.database.ColumnMapRowMapper;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.exception.BPMNError;
import com.awspaas.user.apps.shhtaerospaceindustrial.util.CoreUtil;

/**
 * 
 * @Description:表单办理前校验，检查被访单位的接待人是否存在
 * @author: dingyi
 * @date: 2021年6月28日 上午9:42:30
 */
public class checkVisitorTaegetValidateEvent implements InterruptListenerInterface {

	@Override
	public String getDescription() {

		return "表单办理前校验，被访单位接待人不存在，阻止办理  ";
	}

	@Override
	public String getProvider() {

		return "wanghb";
	}

	@Override
	public String getVersion() {

		return "1.0";
	}

	@Override
	public boolean execute(ProcessExecutionContext processExecutionContext) throws Exception {
		// 获取流程实例ID
		String processInstId = processExecutionContext.getProcessInstance().getId();
		// 根据流程实例ID获取任务表内数据
		List<Map<String, Object>> visitmain = DBSql.query("SELECT * FROM BO_EU_VISITOR_MANAGE WHERE BINDID = ? ",
				new ColumnMapRowMapper(), new Object[] { processInstId });
		List<Map<String, Object>> userinfolist = DBSql.query("SELECT * FROM BO_EU_VISITOR_MANAGE_MX WHERE BINDID = ? ",
				new ColumnMapRowMapper(), new Object[] { processInstId });

		if (userinfolist == null || userinfolist.isEmpty()) {
			throw new BPMNError("人员明细为空，请添加人员信息后提交");
		}

		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String today = sdf.format(date);
		long formatDateL = sdf.parse(today).getTime();
		long inTime = 0;
		long outTime = 0;
		for (Map<String, Object> map : visitmain) {
			String TARGETMAN = CoreUtil.objToStr(map.get("TARGETMAN"));// 被访客姓名
			String TARGETDEPT = CoreUtil.objToStr(map.get("TARGETDEPT"));// 被访部门
			String TARGETUNIT = CoreUtil.objToStr(map.get("TARGETUNIT"));// 被访单位
			String TARGETMANUID = CoreUtil.objToStr(map.get("TARGETMANUID"));// 被访单位
			if (TARGETMANUID != null && TARGETMANUID.equals("")) {
				String queryuser = "SELECT userid  FROM view_sastorginfo WHERE departmentname like  '%" + TARGETDEPT
						+ "%' AND username like  '%" + TARGETMAN + "%'";
				String userid = CoreUtil.objToStr(DBSql.getString(queryuser, "userid"));// 根据部门和姓名查询userid
				if (userid != null && !userid.equals("")) {
					DBSql.update("UPDATE BO_EU_VISITOR_MANAGE SET TARGETMANUID = '" + userid + "' WHERE BINDID = '"
							+ processInstId + "'");

				} else {
					throw new BPMNError("查询不到被访部门的接待人员！");
				}
			}
			if("".equals(TARGETUNIT)) {
				throw new BPMNError("被访问单位不能为空.");
			}
			
			String udate = CoreUtil.objToStr(map.get("INPARTTIME"));// 进入园区日期
			inTime = sdf.parse(udate).getTime();
			outTime = sdf.parse(CoreUtil.objToStr(map.get("OUTPARTTIME"))).getTime();
			System.out.println("本次入园时间"+udate);
			System.out.println("本次出园时间"+CoreUtil.objToStr(map.get("OUTPARTTIME")));
			
			long udateL = sdf.parse(udate).getTime();
			if (udateL < formatDateL) {// 如果进入日期小于系统日期
				throw new BPMNError("预计来访时间不能小于当前时间！");
			}
			String VISITTYPE = CoreUtil.objToStr(map.get("VISITTYPE"));// 被访客姓名
			 if ((outTime - inTime) >= 24 * 3600 * 1000  )
			 {
//				 System.out.print("over one day");
					DBSql.update("UPDATE BO_EU_VISITOR_MANAGE SET VISITTYPE = '短期'  WHERE BINDID = '"+processInstId+"'");

			 }else {
//				 System.out.print("one day");
					DBSql.update("UPDATE BO_EU_VISITOR_MANAGE SET VISITTYPE = '单日'  WHERE BINDID = '"+processInstId+"'");

			 }
			

		}

		List<String> certlist = new ArrayList<String>();
		List<String> celllist = new ArrayList<String>();
		for (Map<String, Object> map : userinfolist) {
			String VISITORNAME = CoreUtil.objToStr(map.get("VISITORNAME"));
			String VISITORCELL = CoreUtil.objToStr(map.get("VISITORCELL"));
			celllist.add(VISITORCELL);
			String CERTNO = CoreUtil.objToStr(map.get("CERTNO"));
			certlist.add(CERTNO);
//			String ABOUTFILE = CoreUtil.objToStr(map.get("ABOUTFILE"));
//
//			if (ABOUTFILE == "") {
//
//				throw new BPMNError("请确认访客：" + VISITORNAME + "的证件照是否上传！");
//			}
			String queryRecordSql = "select t.inparttime, t.outparttime, t.bindid from BO_EU_VISITOR_MANAGE t, BO_EU_VISITOR_MANAGE_MX a where t.bindid = a.bindid"
					+ " and a.certno = '" + CERTNO
					+ "'  and (t.busistatus = 1 or t.busistatus = 2) and to_date(t.outparttime, 'yyyy-MM-dd')>=to_date('"
					+ today +"', 'yyyy-MM-dd') and t.bindid !='"+processInstId+"'";
			System.out.println(queryRecordSql);
			List<Map<String, Object>> RecordList = DBSql.query(queryRecordSql, new ColumnMapRowMapper(),
					new Object[] {});
			//System.out.println("历史记录："+RecordList.size());
			
			for(int i = 0; i< RecordList.size(); i++) {
				Map<String, Object> recordMap = RecordList.get(i);
				//System.out.println("历史进入时间："+CoreUtil.objToStr(recordMap.get("INPARTTIME")));
				//System.out.println("历史离开时间："+CoreUtil.objToStr(recordMap.get("OUTPARTTIME")));
				
				long inTimeH = sdf.parse(CoreUtil.objToStr(recordMap.get("INPARTTIME"))).getTime();
				long outTimeH = sdf.parse(CoreUtil.objToStr(recordMap.get("OUTPARTTIME"))).getTime();
				//System.out.println(inTimeH);
				//System.out.println(outTimeH);
				//System.out.println(inTime);
				//System.out.println(outTime);
				if(!(outTime<inTimeH||inTime>outTimeH)) {
					throw new BPMNError(VISITORNAME+"存在重复预定日期，请重填！");
				}
			}
		}
		long certnocount = certlist.stream().distinct().count();
		List dumplist = certlist.stream()

				.collect(Collectors.toMap(e -> e, e -> 1, Integer::sum))

				.entrySet()

				.stream()

				.filter(e -> e.getValue() > 1)

				.map(Map.Entry::getKey)

				.collect(Collectors.toList());
		if (dumplist.size() > 0) {
			String certstr = "";
			for (Object val : dumplist) {
				certstr = (String) val + ";";
			}
			System.out.println(certstr);
			throw new BPMNError("来访人员中重复身份证号：" + certstr);
		}
		//
//		long cellcount = celllist.stream().distinct().count();
		List dumplist2 = celllist.stream()

				.collect(Collectors.toMap(e -> e, e -> 1, Integer::sum))

				.entrySet()

				.stream()

				.filter(e -> e.getValue() > 1)

				.map(Map.Entry::getKey)

				.collect(Collectors.toList());
		if (dumplist2.size() > 0) {
			String cellstr = "";
			for (Object val : dumplist2) {
				cellstr = (String) val + ";";
			}
			System.out.println(cellstr);
			throw new BPMNError("来访人员中重复手机证号：" + cellstr);
		}

		List<Map<String, Object>> carinfolist = DBSql.query(
				"SELECT * FROM BO_EU_VISITOR_MANAGE_CARMX WHERE BINDID = ? ", new ColumnMapRowMapper(),
				new Object[] { processInstId });
		List<String> carnolist = new ArrayList<String>();

		if (carinfolist.size() > 0) {
			for (Map<String, Object> map : carinfolist) {
				String CARNO = CoreUtil.objToStr(map.get("CARNO"));
				if (CARNO != "") {
					carnolist.add(CARNO);
				}
			}
			long carnocount = carnolist.stream().distinct().count();
			if (carnocount != carnolist.size()) {
				throw new BPMNError("来访车辆信息里有重复车牌号！");
			}
		}
		//身份证号正确性校验
				for (Map<String, Object> usermap : userinfolist) {
					String CERTTYPE = CoreUtil.objToStr(usermap.get("CERTTYPE"));// 证件类型
					String CERTNO = CoreUtil.objToStr(usermap.get("CERTNO"));// 证件号码
					String VISITORNAME = CoreUtil.objToStr(usermap.get("VISITORNAME"));// 姓名
					if("身份证".equals(CERTTYPE) && !"".equals(CERTNO)) {
						if (!isCard(CERTNO)) {
							throw new BPMNError(VISITORNAME+"：身份证号码不正确！");
						}
					}
				}

		return true;
	}
	
	/**
     * 验证身份证真假
     * @param  carNumber 身份证号
     * @return boolean*/
    public static boolean isCard(String carNumber) {
        //判断输入身份证号长度是否合法
        if (carNumber.length() != 18) {
            throw new RuntimeException("身份证长度不合法");//不合法 抛出一个异常
        }
        //校验身份证真假
        int sum = 0;
        int[] weight = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};//将加权因子定义为数组
        //遍历weight数组 求身份证前17项系数和
        for (int i = 0; i < weight.length; i++) {
            int n = carNumber.charAt(i) - 48;//获取 身份证对应数
            int w = weight[i];
            sum += w * n;
        }
        //对11求余
        int index = sum % 11;
        //校验码
        String m = "10X98765432";
        //获取身份证最后一位进行比对
        return m.charAt(index) == carNumber.charAt(17);
    }

}
